const { readFileSync, writeFileSync, readdirSync, unlinkSync } = require('fs')
const { exec } = require('child_process')
const path = require('path')
const envConfig = require('./env_config.json')

const jsonPath = './src/pages.json'
const MainfestJsonPath = './src/manifest.json'
const ProjectConfigJsonPath = './project.config.json'
const routesPath = './src/router/'
const subPackPath = 'src/router/subPack'

// 更改小程序 appid
const setMainfestJson = (newAppid) => {
    // mainfest.json
    const mainfest = readFileSync(MainfestJsonPath, 'utf8')
    const mainfestOldJson = JSON.parse(mainfest)
    const mainfestNewJson = () => {
        const _oldJson = JSON.parse(JSON.stringify(mainfestOldJson))
        _oldJson['mp-weixin'].appid = newAppid
        return JSON.stringify(_oldJson)
    }
    // project.config.json
    const project = readFileSync(ProjectConfigJsonPath, 'utf8')
    const projectOldJson = JSON.parse(project)
    const projectOldJsonNewJson = () => {
        const _oldJson = JSON.parse(JSON.stringify(projectOldJson))
        _oldJson.appid = newAppid
        return JSON.stringify(_oldJson)
    }

    writeFileSync(MainfestJsonPath, mainfestNewJson())
    writeFileSync(ProjectConfigJsonPath, projectOldJsonNewJson())
    console.log('weixin_appid 编译完成！')
}

// 将routes.ts 编译=> .js => 设置pages => 设置subPack => 设置tabBar
const setPagesJson = () => {
    const buildReg = new RegExp('^partner.ts$')
    const files = readdirSync(routesPath)
    let filedir = ''
    files.forEach((fileName) => {
        const _filedir = path.join(routesPath, fileName)
        if (!buildReg.test(fileName)) return
        filedir = _filedir
    })

    // 编译
    const newPages = []
    exec(`tsc ${filedir}`, {}, () => {
        const pagesPath = '../src/router/partner.js'
        // eslint-disable-next-line import/no-dynamic-require
        const page = require(pagesPath)
        page.default.forEach((p) => {
            newPages.push(p)
        })
        // 设置pages tabBar
        changePages(routesFormat(newPages), newPages.filter(i => i.tab).map(i => ({ 'pagePath': i.path })))
        // 设置subPackPages
        const subPack = [...new Set(newPages.map(r => r?.subPack || null).filter(r => !!r))]
        subPack.forEach(newSubPack => {
            changeSubPages(newSubPack, routesFormat(newPages, newSubPack))
        })

        // 删除多余的编译文件
        readdirSync(subPackPath).forEach(file => {
            if (/.js$/.test(file)) {
                unlinkSync(`${subPackPath}/${file}`)
            }
        })

        console.log('pages.json: router 编译完成！')
    })
}

// pages.json router format
function routesFormat(routes, subPack = '') {
    const newRoutes = []
    const add = (route) => {
        const style = {}
        style.navigationBarTitleText = route.title || '美稻AI智客合作'
        if (route.titleBar) {
            style.navigationStyle = 'custom'
        }
        if (route.titleBarConfig) {
            Object.keys(route.titleBarConfig).forEach(key => {
                style[key] = route.titleBarConfig[key]
            })
        }
        newRoutes.push({
            path: route.path,
            style,
        })
    }
    routes.forEach((route) => {
        if (!route?.subPack && subPack === '') {
            add(route)
        }
        if (route?.subPack && route.subPack === subPack) {
            add(route)
        }
    })
    return newRoutes
}

// 更改 pages.json
const changePages = (newPages, newTabBar) => {
    const data = readFileSync(jsonPath, 'utf8')
    const oldJson = JSON.parse(data)
    const newJson = () => {
        const _oldJson = JSON.parse(JSON.stringify(oldJson))
        _oldJson.pages = newPages
        _oldJson.tabBar.list = newTabBar
        _oldJson.subPackages = []
        _oldJson.easycom = {
            autoscan: true,
            // 注意一定要放在custom里，否则无效，https://ask.dcloud.net.cn/question/131175
            custom: {
                '^uni-(.*)': '@dcloudio/uni-ui/lib/uni-$1/uni-$1.vue',
                '^u--(.*)': 'uview-plus/components/u-$1/u-$1.vue',
                '^up-(.*)': 'uview-plus/components/u-$1/u-$1.vue',
                '^u-([^-].*)': 'uview-plus/components/u-$1/u-$1.vue',
            },
        }
        return JSON.stringify(_oldJson)
    }
    writeFileSync(jsonPath, newJson())
}
// 更改分包 pages.json
const changeSubPages = (newSubPack, newSubPages) => {
    const data = readFileSync(jsonPath, 'utf8')
    const oldJson = JSON.parse(data)
    const newJson = () => {
        const _oldJson = JSON.parse(JSON.stringify(oldJson))
        _oldJson.subPackages.push({
            'root': newSubPack,
            'pages': newSubPages,
        })
        return JSON.stringify(_oldJson)
    }
    writeFileSync(jsonPath, newJson())
}

setMainfestJson(envConfig.partner_weixin_appid)
setPagesJson()
